package com.rock.code.common.utils.controller;

import com.rock.code.base.controller.BaseController;
import com.rock.code.common.comm.CommDate;
import com.rock.code.common.exceptions.SystemException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.*;
import java.util.Date;

/**
 * The type Download controller.
 *
 * @author kongqiang
 * @date 2018.01.02
 */
@Controller
@RequestMapping("/file")
public class DownloadController extends BaseController {

	/**
	 * Download file.
	 *
	 * @param filePath the file path
	 * @throws Exception the exception
	 * @author kongqiang
	 * @date 2018.01.02
	 */
	@RequestMapping("/download")
	public void downloadFile(String filePath) throws Exception {
		if (filePath != null) {
			File file = new File(filePath);
			if (file.exists()) {
				String downloadFileName = CommDate.dateToStr(new Date(), CommDate.YMDHMS_S) + ".xls";
				response.setContentType("application/force-download");// 设置强制下载不打开
				response.addHeader("Content-Disposition", "attachment;fileName=" + downloadFileName);// 设置文件名
				byte[] buffer = new byte[1024];
				FileInputStream fis = null;
				BufferedInputStream bis = null;
				try {
					fis = new FileInputStream(file);
					bis = new BufferedInputStream(fis);
					OutputStream os = response.getOutputStream();
					int i = bis.read(buffer);
					while (i != -1) {
						os.write(buffer, 0, i);
						i = bis.read(buffer);
					}
				} catch (Exception e) {
					e.printStackTrace();
					throw new SystemException(e);
				} finally {
					if (bis != null) {
						try {
							bis.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					if (fis != null) {
						try {
							fis.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
	}
	
}
